/*
* Handle admin actions
* create user, delete user, get the stats
* @author INFO-A1
*/

package sopraim.presenter.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.json.Json;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import sopraim.entity.User;
import sopraim.presenter.services.AdminService;
import sopraim.presenter.services.UserService;
import sopraim.presenter.services.util.Contact;

@WebServlet(name = "AdminServlet", urlPatterns = {
    "/createUser",
    "/deleteUser",
    "/performCreateUser",
    "/performDeleteUser",
    "/searchAdmin",
    "/addRight",
    "/removeRight"
})
public class AdminServlet extends HttpServlet {
    AdminService adminService = new AdminService();
    UserService userService = new UserService();
    private String notif ="";
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        String userPath = request.getServletPath();
        User localUser = (User) session.getAttribute("user");
        //Display create user page
        switch (userPath) {
            case "/createUser":
                userPath = "/admin/CreateUser";
                break;
            case "/deleteUser":
                userPath = "/admin/DeleteUser";
                break;
            case "/searchAdmin":
                userPath = "/admin/SetRights";
                String pseudo = request.getParameter("username");
                try {
                    ArrayList<Contact> res = userService.searchContact(localUser, pseudo);
                    request.setAttribute("users", res);
                    
                } catch (Exception ex) {
                    
                }
                break;
            case "/addRight" :
                String u = request.getParameter("username");
                try {
                    adminService.setRights("admin", u, true);
                } catch (Exception ex) {
                    Logger.getLogger(AdminServlet.class.getName()).log(Level.SEVERE, null, ex);
                }
                userPath = "/admin/SetRights";
                break;
            case "/removeRight" :
                String n = request.getParameter("username");
                try {
                    adminService.setRights("admin", n, false);
                } catch (Exception ex) {
                    Logger.getLogger(AdminServlet.class.getName()).log(Level.SEVERE, null, ex);
                }
                userPath = "/admin/SetRights";
                break;
            case "/performCreateUser":
            {
                //retrieve the parameters
                String username=request.getParameter("pseudo");
                String email=request.getParameter("email");
                String name=request.getParameter("name");
                String firstname=request.getParameter("firstname");
                String location=request.getParameter("location");
                boolean isAdmin=Boolean.parseBoolean(request.getParameter("isadmin"));
                String adminUsername = localUser.getUsername();
                //store the user in the database
                boolean error = false;
                try{
                    adminService.createAccount("admin", username, email, name, firstname, isAdmin, location);
                }
                catch(Exception e){
                    error = true;
                }
                PrintWriter out =  response.getWriter();
                out.print(Json.createObjectBuilder().add("error",error).build());
                out.flush();
                out.close();
                return;
                
            }
            //delete user
            case "/performDeleteUser":
            {
                String name = request.getParameter("username");
                boolean error = false;
                try{
                    adminService.deleteAccount("admin", name);
                    
                }
                catch(Exception e){
                    error = true;
                }
                PrintWriter out =  response.getWriter();
                out.print(Json.createObjectBuilder().add("error",error).build());
                out.flush();
                out.close();
                return;
                
            }
            
        }
        String page ="/WEB-INF"+userPath+".jsp";
        request.getRequestDispatcher(page).forward(request, response);
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
}
